﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace cls.u_Models
{
    public partial class ShowBackorder : System.Web.UI.Page
    {
        static String UserName = "";
        static String OrgCode = "";
        static String ClsCode = "";
        static String PluCode = "";

        static Boolean IsUserInZb = false;

        protected void Page_Load(object sender, EventArgs e)
        {
            UserName = User.Identity.Name;
            OrgCode = DropDownList_SelectOrgCode.SelectedValue;

            IsUserInZb = UserInZB(UserName);

            //清空错误信息
            Label_ErrorMsg.Text = "";

            if (!Page.IsPostBack)
            {
                //ClsCode默认值“全部”
                //TextBox_InputClsCode.Text = "全部";
                //TextBox_InputClsCode.Width = 60;
                //TextBox_InputClsCode.Font.Size = 8;

                //PluCode默认值"全部"
                TextBox_InputPluCode.Text = "全部";
                TextBox_InputPluCode.Width = 60;
                TextBox_InputPluCode.Font.Size = 8;

                //GridView_BackorderDetail.Enabled = true;
                DropdownList_ShowOrgNames();

                //清空批量回复的PluCode和Msg
                TextBox_MRespPluCode.Text = "";
                TextBox_MutiRespMsg.Text = "";
            }
        }

        protected Boolean UserInZB(String UserName)
        {
            Boolean UserInZB = false;

            SqlConnection SqlConnection = new SqlConnection("Data Source=192.168.0.241;Initial Catalog=cls_forms_db;Persist Security Info=True;User ID=sa;Password=My.SA");
            SqlConnection.Open();

            SqlCommand SelectCommand = new SqlCommand("SELECT OrgId FROM [dbo].[u_cls_UserInOrg] WHERE UserName=@UserName", SqlConnection);

            SelectCommand.Parameters.Add("@UserName", SqlDbType.NVarChar, 4);
            SelectCommand.Parameters["@UserName"].Value = UserName;

            SqlDataReader OrgIdReader = SelectCommand.ExecuteReader();

            while (OrgIdReader.Read())
            {
                //ZB的OrgId是AD401DCA-D653-4A9D-9D90-E5B74B6B7CE3
                //注意字符串是小写形式！
                if (OrgIdReader["OrgId"].ToString().Equals("ad401dca-d653-4a9d-9d90-e5b74b6b7ce3"))
                {
                    //Label_ErrorMsg.Text = OrgIdReader["OrgId"].ToString();
                    UserInZB = true;
                }
                else
                {
                    //Label_ErrorMsg.Text = OrgIdReader["OrgId"].ToString();
                    UserInZB = false;
                }
            }

            //Label_ErrorMsg.Visible = true;

            OrgIdReader.Close();
            SelectCommand.Dispose();
            SqlConnection.Close();

            return UserInZB;
        }

        protected DataSet BackorderDetailDataSet(String OrgCode, String ClsCode, String PluCode, String LastInsDatetime)
        {
            //OrgCode = DropDownList_SelectOrgCode.SelectedValue;

            DataSet BackorderDetailDataSet = new DataSet();

            SqlConnection SqlConnection = new SqlConnection("Data Source=192.168.0.241;Initial Catalog=cls_forms_db;Persist Security Info=True;User ID=sa;Password=My.SA");
            SqlConnection.Open();

            //2015-01-12，更新模版
            //String SelectString = "SELECT [Id],[OrgCode],[OrgName],[ClsCode],[ClsName],[PluCode],[PluName],[BarCode],[PluType],[SkillCount],[SkillPrice],[AVG_DaySale],[ST_Days],[CT_Days],[Comment],[CommCase],[ConfName],[DoneDatatime],[CommMark],[ClsResp],[ImportDatatime] FROM [dbo].[u_cls_Backorder_Table] WHERE [ImportDatatime] = '" + LastInsDatetime + "'";

            //临时取消[ImportDatatime]
            String SelectString = "SELECT [Id],[OrgCode],[OrgName],[ClsCode],[ClsName],[PluCode],[PluName],[LW_SaleCount],[SkillCount],[CommCase],[YH_BillNo],[YH_Count],[Comment],[ConfName],[DoneFlag],[DoneDatatime],[CommMark],[ClsResp],[ImportDatatime] FROM [dbo].[u_cls_Backorder_Table] WHERE [ImportDatatime] = '" + LastInsDatetime + "'";
            //String SelectString = "SELECT [Id],[OrgCode],[OrgName],[ClsCode],[ClsName],[PluCode],[PluName],[LW_SaleCount],[SkillCount],[CommCase],[YH_BillNo],[YH_Count],[Comment],[ConfName],[DoneFlag],[DoneDatatime],[CommMark],[ClsResp],[ImportDatatime] FROM [dbo].[u_cls_Backorder_Table] WHERE 1=1";

            //是否选择了OrgCode
            if (OrgCode.Equals("all"))
            {
                SelectString = "SELECT [Id],[OrgCode],[OrgName],[ClsCode],[ClsName],[PluCode],[PluName],[LW_SaleCount],[SkillCount],[CommCase],[YH_BillNo],[YH_Count],[Comment],[ConfName],[DoneFlag],[DoneDatatime],[CommMark],[ClsResp],[ImportDatatime] FROM [dbo].[u_cls_Backorder_Table] WHERE ImportDatatime IN (SELECT LastInsDatetime FROM (SELECT OrgCode, LastInsDatetime FROM [dbo].[u_cls_LastInsDatetime] WHERE ApplicationName = 'Backorder' GROUP BY OrgCode,LastInsDatetime) LID)";
            }
            else
            {
                SelectString += " AND OrgCode='" + OrgCode + "'";
            }

            //是否输入了ClsCode            
            //if (ClsCode.Equals("全部"))
            //{ }
            //else if (ClsCode.StartsWith("%"))
            //{
            //    SelectString += " AND ClsCode LIKE '" + ClsCode + "'";
            //}
            //else if (ClsCode.EndsWith("%"))
            //{
            //    SelectString += " AND ClsCode LIKE '" + ClsCode + "'";
            //}
            //else
            //{
            //    SelectString += " AND ClsCode LIKE '%" + ClsCode + "%'";
            //}

            //2015-01-14，更新了LIKE语法
            if (ClsCode.Equals("0"))
            { }
            else
            {
                SelectString += " AND ClsCode LIKE '" + ClsCode + "%'";
            }

            //是否输入了PluCode
            if (PluCode.Equals("全部"))
            { }
            else if (PluCode.StartsWith("%"))
            {
                SelectString += " AND PluCode LIKE '%" + PluCode + "'";
            }
            else if (PluCode.EndsWith("%"))
            {
                SelectString += " AND PluCode LIKE '" + PluCode + "%'";
            }
            else
            {
                SelectString += " AND PluCode LIKE '%" + PluCode + "%'";
            }

            //SelectString += " ORDER BY OrgCode,PluCode";

            SqlDataAdapter dataAdapter = new SqlDataAdapter(SelectString, SqlConnection);
            dataAdapter.Fill(BackorderDetailDataSet);

            dataAdapter.Dispose();
            SqlConnection.Close();

            //2015-01-15，ClsCode列增加排序
            //BackorderDetailDataSet.DefaultViewManager.
            //BackorderDetailDataSet.DefaultViewManager
            //参考
            //http://msdn.microsoft.com/zh-cn/library/4xz507ds(v=vs.110).aspx
            //DataViewManager viewManager = new DataViewManager(BackorderDetailDataSet);
            //BackorderDetailDataSet.Tables[0].DefaultView = so

            return BackorderDetailDataSet;
        }

        protected String GetLastInsDatetime(String OrgCode)
        {
            String LastInsDatetime = "";
            String SelectCommandString = "SELECT TOP(1) LastInsDatetime FROM [dbo].[u_cls_LastInsDatetime] WHERE OrgCode = '" + OrgCode + "' AND ApplicationName = 'Backorder' ORDER BY LastInsDatetime DESC";

            SqlConnection SqlConnection = new SqlConnection("Data Source=192.168.0.241;Initial Catalog=cls_forms_db;Persist Security Info=True;User ID=sa;Password=My.SA");
            SqlConnection.Open();

            //总部上传改为门店上传
            //需要取得每个门店的最后上传时间
            //或者Insert之前先Delete，WHERE OrgCode
            SqlCommand SelectCommand = new SqlCommand(SelectCommandString, SqlConnection);
            SqlDataReader LastInsDatetimeReader = SelectCommand.ExecuteReader();

            //酱紫写法系错误嘀，乖乖的用While循环吧......
            //if(LastInsDatetimeReader.HasRows)
            //{
            //    LastInsDatetime = LastInsDatetimeReader["LastInsDatetime"].ToString();
            //}
            while (LastInsDatetimeReader.Read())
            {
                //ToString()丢失精度，"yyyyMMdd-hh:mm:ss.fff"
                //LastInsDatetime = LastInsDatetimeReader["LastInsDatetime"].ToString();
                //参考
                //http://msdn.microsoft.com/zh-cn/library/bb882581(v=vs.110).aspx
                //http://msdn.microsoft.com/zh-cn/library/zdtaw1bw(v=vs.110).aspx
                //http://msdn.microsoft.com/zh-cn/library/system.data.sqlclient.sqldatareader.getdatetime(v=vs.110).aspx
                //http://forums.asp.net/t/1065058.aspx?using+SqlDataReader+to+retrieve+datetime+values
                LastInsDatetime = LastInsDatetimeReader.GetDateTime(0).ToString("yyyy-MM-dd HH:mm:ss.fff");
            }

            LastInsDatetimeReader.Close();
            SqlConnection.Close();

            //调试信息
            //Label_ErrorMsg.Text = LastInsDatetime;

            return LastInsDatetime;
        }

        protected String GetOrgIdByUserName(String UserName)
        {
            String OrgId = "";

            SqlConnection SqlConnection = new SqlConnection("Data Source=192.168.0.241;Initial Catalog=cls_forms_db;Persist Security Info=True;User ID=sa;Password=My.SA");
            SqlConnection.Open();

            SqlCommand SelectCommand = new SqlCommand("SELECT [OrgId] FROM [dbo].[u_cls_UserInOrg] WHERE [UserName] = @UserName", SqlConnection);

            SelectCommand.Parameters.Add("@UserName", SqlDbType.NVarChar, 4);
            SelectCommand.Parameters["@UserName"].Value = UserName;

            SqlDataReader OrgIdReader = SelectCommand.ExecuteReader();

            while (OrgIdReader.Read())
            {
                OrgId = OrgIdReader["OrgId"].ToString().ToUpper();
            }

            OrgIdReader.Close();
            SelectCommand.Dispose();
            SqlConnection.Close();

            return OrgId;
        }

        protected void GridView_BackorderDetail_DataBind(String OrgCode, String ClsCode, String PluCode, String ColumnSortDirection)
        {
            //2015-01-15，ClsCode列增加排序
            //使用DataView
            DataView DataSetDV = new DataView();
            DataSetDV.Table = BackorderDetailDataSet(OrgCode, ClsCode, PluCode, GetLastInsDatetime(OrgCode)).Tables[0];

            if (ColumnSortDirection.Equals(""))
            {
                ColumnSortDirection = "ASC";
            }
            else if (ColumnSortDirection.Equals("Ascending"))
            {
                ColumnSortDirection = "ASC";
            }
            else if (ColumnSortDirection.Equals("Descending"))
            {
                ColumnSortDirection = "DESC";
            }
            else
            {
                ColumnSortDirection = "ASC";
            }
            DataSetDV.Sort = "ClsCode " + ColumnSortDirection;

            GridView_BackorderDetail.AutoGenerateColumns = false;
            GridView_BackorderDetail.Columns.Clear();

            //2015-01-15，ClsCode列增加排序，是要使用DataView作为DataSource
            //GridView_BackorderDetail.DataSource = BackorderDetailDataSet(OrgCode, ClsCode, PluCode, GetLastInsDatetime(OrgCode));            
            GridView_BackorderDetail.DataSource = DataSetDV;

            GridView_BackorderDetail.DataKeyNames = new string[] { "id" };

            //[0]
            BoundField bField;
            bField = new BoundField();
            bField.DataField = "id";
            bField.HeaderText = "编号";
            bField.ReadOnly = true;
            GridView_BackorderDetail.Columns.Add(bField);

            //[1]
            bField = new BoundField();
            bField.DataField = "OrgCode";
            bField.HeaderText = "组织编码";
            bField.HeaderStyle.HorizontalAlign = HorizontalAlign.Center;
            bField.HeaderStyle.Wrap = false;
            bField.ReadOnly = true;
            bField.ItemStyle.HorizontalAlign = HorizontalAlign.Center;
            //bField.ItemStyle.Width = 20;
            bField.ItemStyle.Wrap = false;
            GridView_BackorderDetail.Columns.Add(bField);

            //[2]
            bField = new BoundField();
            bField.DataField = "OrgName";
            bField.HeaderText = "组织名称";
            bField.ReadOnly = true;
            GridView_BackorderDetail.Columns.Add(bField);

            //[3]
            bField = new BoundField();
            bField.DataField = "ClsCode";

            //根据排序方向设置列HeaderText
            if (ColumnSortDirection.Equals("ASC"))
            {
                bField.HeaderText = "品类编码 [▲]";
            }
            else if (ColumnSortDirection.Equals("DESC"))
            {
                bField.HeaderText = "品类编码 [▼]";
            }
            else
            {
                bField.HeaderText = "品类编码";
            }

            //2015-01-16，增加排序
            bField.SortExpression = "ClsCode";

            bField.ReadOnly = true;
            GridView_BackorderDetail.Columns.Add(bField);

            //[4]
            bField = new BoundField();
            bField.DataField = "ClsName";
            bField.HeaderText = "品类名称";
            bField.ReadOnly = true;
            bField.Visible = false;
            GridView_BackorderDetail.Columns.Add(bField);

            //[5]
            bField = new BoundField();
            bField.DataField = "PluCode";
            bField.HeaderText = "商品编码";
            bField.ReadOnly = true;
            GridView_BackorderDetail.Columns.Add(bField);

            //[6]
            bField = new BoundField();
            bField.DataField = "PluName";
            bField.HeaderText = "商品名称";
            bField.ReadOnly = true;
            GridView_BackorderDetail.Columns.Add(bField);

            //bField = new BoundField();
            //bField.DataField = "BarCode";
            //bField.HeaderText = "商品条码";
            //bField.ReadOnly = true;
            //bField.Visible = false;
            //GridView_BackorderDetail.Columns.Add(bField);

            //bField = new BoundField();
            //bField.DataField = "PluType";
            //bField.HeaderText = "商品类型";
            //bField.ReadOnly = true;
            //GridView_BackorderDetail.Columns.Add(bField);

            //[7]
            bField = new BoundField();
            bField.DataField = "SkillCount";
            bField.HeaderText = "库存数量";
            bField.ReadOnly = true;
            GridView_BackorderDetail.Columns.Add(bField);

            //[8]
            bField = new BoundField();
            bField.DataField = "LW_SaleCount";
            bField.HeaderText = "上周销量";
            bField.ReadOnly = true;
            bField.Visible = false;
            GridView_BackorderDetail.Columns.Add(bField);

            //[9]
            //bField = new BoundField();
            //bField.DataField = "SkillCount";
            //bField.HeaderText = "库存";
            //bField.ReadOnly = true;
            //GridView_BackorderDetail.Columns.Add(bField);

            //bField = new BoundField();
            //bField.DataField = "ST_Days";
            //bField.HeaderText = "可销天数";
            //bField.ReadOnly = true;
            //GridView_BackorderDetail.Columns.Add(bField);

            //bField = new BoundField();
            //bField.DataField = "CT_Days";
            //bField.HeaderText = "未销天数";
            //bField.ReadOnly = true;
            //GridView_BackorderDetail.Columns.Add(bField);

            //[10]
            bField = new BoundField();
            bField.DataField = "Comment";
            bField.HeaderText = "原因";
            //总部不可编辑，门店可编辑
            //bField.ReadOnly = true;           
            bField.ReadOnly = UserInZB(UserName);
            GridView_BackorderDetail.Columns.Add(bField);

            //[11]
            bField = new BoundField();
            bField.DataField = "YH_BillNo";
            bField.HeaderText = "要货单号";
            //不可编辑
            bField.ReadOnly = true;
            //bField.ReadOnly = UserInZB(UserName);
            GridView_BackorderDetail.Columns.Add(bField);

            //[12]
            bField = new BoundField();
            bField.DataField = "YH_Count";
            bField.HeaderText = "要货数量";
            //不可编辑
            bField.ReadOnly = true;
            //bField.ReadOnly = UserInZB(UserName);
            //bField.Visible = false;
            GridView_BackorderDetail.Columns.Add(bField);

            //[13]
            bField = new BoundField();
            bField.DataField = "DoneDatatime";
            bField.HeaderText = "完成时间";
            //总部不可编辑，门店可编辑
            //bField.ReadOnly = true;
            bField.ReadOnly = UserInZB(UserName);
            bField.Visible = false;
            GridView_BackorderDetail.Columns.Add(bField);

            //[14]
            bField = new BoundField();
            bField.DataField = "CommMark";
            bField.HeaderText = "备注";
            //总部不可编辑，门店可编辑
            //bField.ReadOnly = true;
            bField.ReadOnly = UserInZB(UserName);
            bField.Visible = false;
            GridView_BackorderDetail.Columns.Add(bField);

            //[15]
            bField = new BoundField();
            bField.DataField = "ClsResp";
            bField.HeaderText = "品类部回复";
            //总部可编辑，门店不可编辑
            //bField.ReadOnly = true;
            bField.ReadOnly = !UserInZB(UserName);
            GridView_BackorderDetail.Columns.Add(bField);

            //[11]
            //门店显示[已到货]按钮列；总部只显示列值[未到货；已到货]
            //总部不显示
            //ButtonField 类参考
            //http://msdn.microsoft.com/zh-cn/library/system.web.ui.webcontrols.buttonfield(v=vs.110).aspx

            //CommandField cfEdit = new CommandField();
            //cfEdit.ButtonType = ButtonType.Link;
            //cfEdit.EditText = "编辑";
            //cfEdit.ShowEditButton = true;
            //cfEdit.UpdateText = "已到货";
            //cfEdit.CancelText = "取消";
            //cfEdit.Visible = UserInZB(UserName);
            //cfEdit.ItemStyle.Wrap = false;
            //GridView_BackorderDetail.Columns.Add(cfEdit);

            //[16]
            if (IsUserInZb == false)
            {
                ButtonField bfDoneFlag = new ButtonField();

                bfDoneFlag.DataTextField = "DoneFlag";
                bfDoneFlag.HeaderText = "到货确认";
                bfDoneFlag.ShowHeader = true;

                //考虑GridView的DataBound()方法
                //这个if(){}else{}无效
                //if (getDoneFlafValue(OrgCode).Equals("0"))
                //{
                bfDoneFlag.CommandName = "DoneFlag";
                //bfDoneFlag.ButtonType = ButtonType.Button;
                bfDoneFlag.ButtonType = ButtonType.Link;
                bfDoneFlag.Text = "已到货";

                //}
                //else
                //{
                //    bfDoneFlag.Text = "已到货";
                //}
                GridView_BackorderDetail.Columns.Add(bfDoneFlag);
            }
            else
            {
                bField = new BoundField();
                bField.DataField = "DoneFlag";
                bField.HeaderText = "到货确认";
                //总部不可编辑，门店可编辑
                //bField.ReadOnly = true;
                bField.ReadOnly = UserInZB(UserName);
                //bField.Visible = false;
                GridView_BackorderDetail.Columns.Add(bField);
            }
            //ButtonColumn DoneFlagBc = new ButtonColumn();
            //DoneFlagBc.ButtonType = ButtonColumnType.PushButton;
            //DoneFlagBc.Text = "已到货";
            //GridView_BackorderDetail.Columns.Add(DoneFlagBc);

            //[17]
            //显示[编辑]列
            CommandField ZBEdit = new CommandField();
            ZBEdit.ButtonType = ButtonType.Link;

            //门店修改原因；总部修改回复
            if (IsUserInZb == false)
            {
                ZBEdit.HeaderText = "修改原因";
            }
            else
            {
                ZBEdit.HeaderText = "修改回复";
            }
            ZBEdit.EditText = "编辑";
            ZBEdit.ShowHeader = true;
            ZBEdit.ShowEditButton = true;
            ZBEdit.UpdateText = "更新";
            ZBEdit.CancelText = "取消";
            ZBEdit.ItemStyle.Wrap = false;
            GridView_BackorderDetail.Columns.Add(ZBEdit);

            //门店上传时间
            bField = new BoundField();
            bField.DataField = "ImportDatatime";
            bField.HeaderText = "上传时间";
            bField.ReadOnly = true;
            GridView_BackorderDetail.Columns.Add(bField);

            //隐藏id列
            GridView_BackorderDetail.Columns[0].Visible = false;

            //显示分页
            //分页必须PageIndexChanging事件
            GridView_BackorderDetail.AllowPaging = true;
            //每页显示100条记录
            GridView_BackorderDetail.PageSize = 100;

            //2015-01-15，ClsCode列增加排序
            //增加Attributes的SortDirection，用于GridView_BackorderDetail_ColumnsSorting()方法中的排序方向比较
            GridView_BackorderDetail.Attributes.Add("SortDirection", ColumnSortDirection);

            GridView_BackorderDetail.DataBind();
        }

        protected String getDoneFlafValue(String OrgCode)
        {
            String DoneFlafValue = "";

            return DoneFlafValue;
        }

        //2015-01-15，ClsCode列增加排序
        //参考
        //http://msdn.microsoft.com/zh-cn/library/system.web.ui.webcontrols.gridview.sortexpression(v=vs.110).aspx
        protected void GridView_BackorderDetail_RowCreated(Object sender, GridViewRowEventArgs e)
        {
            // Use the RowType property to determine whether the 
            // row being created is the header row. 
            //if (e.Row.RowType == DataControlRowType.Header)
            //{
            //    // Call the GetSortColumnIndex helper method to determine
            //    // the index of the column being sorted.
            //    int sortColumnIndex = GetSortColumnIndex();

            //    if (sortColumnIndex != -1)
            //    {
            //        // Call the AddSortImage helper method to add
            //        // a sort direction image to the appropriate
            //        // column header. 
            //        // 加入排序箭头图片
            //        //AddSortImage(sortColumnIndex, e.Row);
            //    }
            //}
        }
        protected void GridView_BackorderDetail_RowCommand(Object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName == "DoneFlag")
            {
                //参考
                //http://msdn.microsoft.com/zh-cn/library/system.web.ui.webcontrols.buttonfield.datatextfield(v=vs.110).aspx

                // Convert the row index stored in the CommandArgument
                // property to an Integer.
                int index = Convert.ToInt32(e.CommandArgument);

                // Get the last name of the selected author from the appropriate
                // cell in the GridView control.
                GridViewRow selectedRow = GridView_BackorderDetail.Rows[index];
                //TableCell lastNameCell = selectedRow.Cells[1];
                //string lastName = lastNameCell.Text;

                // Display the selected author.
                //Message.Text = "You selected " + lastName + ".";

                //更新DoneFlag标记
                String id = GridView_BackorderDetail.DataKeys[index]["id"].ToString();
                GridView_BackorderDetail_RowUpdateDoneFlag(id);

                //更新单元格内的文本                
                //selectedRow.Cells[11].Text = "已到货";
            }
        }

        protected void GridView_BackorderDetail_RowEditing(object sender, GridViewEditEventArgs e)
        {


            //Set the edit index.
            GridView_BackorderDetail.EditIndex = e.NewEditIndex;

            //编辑状态的行样式
            //GridView_BackorderDetail.EditRowStyle.Width = 40;

            //编辑状态行焦点
            //参考资料
            //http://aspadvice.com/blogs/joteke/archive/2007/02/17/Simple-tips_3A00_-Set-Focus-to-TextBox-in-GridView-_2800_edit-mode_2900_.aspx
            //http://asp.net.bigresource.com/GridView-Lost-focus-in-edit-mode--9Dh27YmEW.html
            //回想一下，我不是要焦点，我是想Scroll到Edit的行
            //最后有效的方法是：
            //http://stackoverflow.com/questions/16152001/asp-net-c-sharp-gridview-focus-on-rowediting
            //MaintainScrollPositionOnPostback="true"
            //
            //以下无效
            //GridView_BackorderDetail.Rows[e.NewEditIndex].Cells[0].Controls[0].Focus();
            //GridViewRow FocusRow = GridView_BackorderDetail.SelectedRow;
            //FocusRow.Cells[0].Focus();
            //GridView_BackorderDetail.Rows[e.NewEditIndex].Controls.

            //Bind data to the GridView control. 
            //必须
            GridView_BackorderDetail_DataBind(OrgCode, ClsCode, PluCode, GridView_BackorderDetail.SortDirection.ToString());
        }

        protected void GridView_BackorderDetail_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
        {
            //不是必须赋值
            //如用户删除TextBox内文本，会造成ClsCode = ""。
            //OrgCode = DropDownList_SelectOrgCode.SelectedValue;
            //ClsCode = TextBox_InputClsCode.Text;
            //PluCode = TextBox_InputPluCode.Text;

            //Reset the edit index.
            GridView_BackorderDetail.EditIndex = -1;

            //Bind data to the GridView control.
            GridView_BackorderDetail_DataBind(OrgCode, ClsCode, PluCode, GridView_BackorderDetail.SortDirection.ToString());
        }

        protected void GridView_BackorderDetail_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
            String id = GridView_BackorderDetail.DataKeys[e.RowIndex]["id"].ToString();

            //总部编辑[15][ClsResp]列
            //门店编辑[10][Comment]列
            if (UserInZB(UserName))
            {
                //调试信息，显示RowIndex
                //Label_ErrorMsg.Text = id;

                //编辑状态的单元格（即TextBox）取值[ClsResp]            
                try
                {
                    String ClsResp = ((TextBox)GridView_BackorderDetail.Rows[e.RowIndex].Cells[14].Controls[0]).Text;

                    GridView_BackorderDetail_RowUpdate(true, id, null, null, null, null, null, ClsResp);
                    GridView_BackorderDetail.EditIndex = -1;
                }
                catch (ArgumentOutOfRangeException getClsRespStringErr)
                {
                    //调试信息，显示ClsResp
                    Label_ErrorMsg.ForeColor = Color.Red;
                    Label_ErrorMsg.Text = "更新回复内容失败：e.RowIndex=" + e.RowIndex + "，信息：  ";
                    Label_ErrorMsg.Text += getClsRespStringErr.Message;
                }
            }
            else
            {
                try
                {
                    String Comment = ((TextBox)GridView_BackorderDetail.Rows[e.RowIndex].Cells[10].Controls[0]).Text;
                    //String CommCase = ((TextBox)GridView_BackorderDetail.Rows[e.RowIndex].Cells[14].Controls[0]).Text;
                    //String ConfName = ((TextBox)GridView_BackorderDetail.Rows[e.RowIndex].Cells[15].Controls[0]).Text;
                    //String DoneDatatime = ((TextBox)GridView_BackorderDetail.Rows[e.RowIndex].Cells[16].Controls[0]).Text;
                    //String CommMark = ((TextBox)GridView_BackorderDetail.Rows[e.RowIndex].Cells[17].Controls[0]).Text;

                    //GridView_BackorderDetail_RowUpdate(false, id, Comment, CommCase, ConfName, DoneDatatime, CommMark, null);

                    GridView_BackorderDetail_RowUpdate(false, id, Comment, null, null, null, null, null);
                    GridView_BackorderDetail.EditIndex = -1;
                }
                catch (ArgumentOutOfRangeException getCommentStringErr)
                {
                    Label_ErrorMsg.ForeColor = Color.Red;
                    Label_ErrorMsg.Text = "更新原因内容失败：e.RowIndex=" + e.RowIndex + "，信息：  ";
                    Label_ErrorMsg.Text += getCommentStringErr.Message;
                }
            }

            //Reset the edit index.
            GridView_BackorderDetail.EditIndex = -1;

            GridView_BackorderDetail_DataBind(OrgCode, ClsCode, PluCode, GridView_BackorderDetail.SortDirection.ToString());
        }

        protected void GridView_BackorderDetail_RowUpdate(Boolean UserInZB, String id, String Comment, String CommCase, String ConfName, String DoneDatatime, String CommMark, String ClsResp)
        {
            SqlConnection SqlConnection = new SqlConnection("Data Source=192.168.0.241;Initial Catalog=cls_forms_db;Persist Security Info=True;User ID=sa;Password=My.SA");
            SqlConnection.Open();

            SqlCommand UpdateCommand = new SqlCommand();

            String UpdateString = "";
            if (UserInZB)
            {
                UpdateString = "UPDATE [dbo].[u_cls_Backorder_Table] SET [ClsResp] = @ClsResp WHERE [Id] = @Id";
                UpdateCommand.CommandText = UpdateString;
                UpdateCommand.CommandType = CommandType.Text;
                UpdateCommand.Connection = SqlConnection;

                UpdateCommand.Parameters.Add("@id", SqlDbType.UniqueIdentifier);
                UpdateCommand.Parameters.Add("@ClsResp", SqlDbType.NVarChar, 4000);

                //必须转换
                //Exception Details: System.InvalidCastException: Invalid cast from 'System.String' to 'System.Guid'.
                UpdateCommand.Parameters["@id"].Value = new System.Guid(id);
                UpdateCommand.Parameters["@ClsResp"].Value = ClsResp;

                //UpdateCommand.ExecuteNonQuery();
            }
            else
            {
                //UpdateString = "UPDATE [dbo].[u_cls_Backorder_Table] SET [Comment] = @Comment,[CommCase] = @CommCase,[ConfName] = @ConfName,[DoneDatatime] = @DoneDatatime,[CommMark] = @CommMark WHERE [Id]=@Id";
                UpdateString = "UPDATE [dbo].[u_cls_Backorder_Table] SET [Comment] = @Comment WHERE [Id]=@Id";
                UpdateCommand.CommandText = UpdateString;
                UpdateCommand.CommandType = CommandType.Text;
                UpdateCommand.Connection = SqlConnection;

                UpdateCommand.Parameters.Add("@id", SqlDbType.UniqueIdentifier);
                UpdateCommand.Parameters.Add("@Comment", SqlDbType.NVarChar, 4000);
                //UpdateCommand.Parameters.Add("@CommCase", SqlDbType.NVarChar, 4000);
                //UpdateCommand.Parameters.Add("@ConfName", SqlDbType.NVarChar, 5);
                //UpdateCommand.Parameters.Add("@DoneDatatime", SqlDbType.NVarChar, 40);
                //UpdateCommand.Parameters.Add("@CommMark", SqlDbType.NVarChar, 4000);

                UpdateCommand.Parameters["@id"].Value = new System.Guid(id);
                UpdateCommand.Parameters["@Comment"].Value = Comment;
                //UpdateCommand.Parameters["@CommCase"].Value = CommCase;
                //UpdateCommand.Parameters["@ConfName"].Value = ConfName;
                //UpdateCommand.Parameters["@DoneDatatime"].Value = DoneDatatime;
                //UpdateCommand.Parameters["@CommMark"].Value = CommMark;

                //UpdateCommand.ExecuteNonQuery();
            }

            try
            {
                UpdateCommand.ExecuteNonQuery();
            }
            catch (SqlException se)
            {
                Label_ErrorMsg.Text = se.Message;
                Label_ErrorMsg.Visible = true;
            }

            UpdateCommand.Dispose();
            SqlConnection.Close();
        }

        //更新DoneFlag列的值
        protected void GridView_BackorderDetail_RowUpdateDoneFlag(String id)
        {
            SqlConnection SqlConnection = new SqlConnection("Data Source=192.168.0.241;Initial Catalog=cls_forms_db;Persist Security Info=True;User ID=sa;Password=My.SA");
            SqlConnection.Open();

            SqlCommand UpdateCommand = new SqlCommand();

            String UpdateString = "";

            UpdateString = "UPDATE [dbo].[u_cls_Backorder_Table] SET [DoneFlag] = @DoneFlagValue WHERE [Id] = @Id";
            UpdateCommand.CommandText = UpdateString;
            UpdateCommand.CommandType = CommandType.Text;
            UpdateCommand.Connection = SqlConnection;

            UpdateCommand.Parameters.Add("@id", SqlDbType.UniqueIdentifier);
            UpdateCommand.Parameters.Add("@DoneFlagValue", SqlDbType.VarChar, 6);

            //必须转换
            //Exception Details: System.InvalidCastException: Invalid cast from 'System.String' to 'System.Guid'.
            UpdateCommand.Parameters["@id"].Value = new System.Guid(id);
            UpdateCommand.Parameters["@DoneFlagValue"].Value = "已到货";

            //UpdateCommand.ExecuteNonQuery();


            try
            {
                UpdateCommand.ExecuteNonQuery();
            }
            catch (SqlException se)
            {
                Label_ErrorMsg.Text = se.Message;
                Label_ErrorMsg.Visible = true;
            }

            UpdateCommand.Dispose();
            SqlConnection.Close();

            GridView_BackorderDetail_DataBind(OrgCode, ClsCode, PluCode, GridView_BackorderDetail.SortDirection.ToString());
        }

        protected void GridView_BackorderDetail_PageIndexChanging(Object sender, GridViewPageEventArgs e)
        {
            if (e == null)
            {
                throw new ArgumentNullException("方法抛出异常：protected void GridView_BackorderDetail_PageIndexChanging(Object sender, GridViewPageEventArgs e)，e == null");
            }

            GridView_BackorderDetail.PageIndex = e.NewPageIndex;

            OrgCode = DropDownList_SelectOrgCode.SelectedValue;

            //ClsCode = TextBox_InputClsCode.Text;
            ClsCode = DropDownList_InputClsCode.SelectedValue;

            PluCode = TextBox_InputPluCode.Text;

            if (ClsCode.Equals(""))
            {
                ClsCode = "全部";
            }
            if (PluCode.Equals(""))
            {
                PluCode = "全部";
            }

            GridView_BackorderDetail_DataBind(OrgCode, ClsCode, PluCode, GridView_BackorderDetail.SortDirection.ToString());
        }

        //2015-01-15，ClsCode列增加排序
        protected void GridView_BackorderDetail_ColumnsSorting(Object sender, GridViewSortEventArgs e)
        {
            String ColumnSortDirection = e.SortDirection.ToString();
            String GV_BackorderDetailAttributes = GridView_BackorderDetail.Attributes["SortDirection"];

            if (GV_BackorderDetailAttributes.Equals("ASC"))
            {
                GV_BackorderDetailAttributes = "Ascending";
            }
            else
            {
                GV_BackorderDetailAttributes = "Descending";
            }

            //调试信息
            //Label_ErrorMsg.Text = "ColumnSortDirection: " + ColumnSortDirection + "<br />";
            //Label_ErrorMsg.Text += "GridView_BackorderDetail.SortDirection: " + GridView_BackorderDetail.SortDirection.ToString() + "<br />";
            //Label_ErrorMsg.Text += "GridView_BackorderDetail.Attributes[\"SortDirection\"]: " + GridView_BackorderDetail.Attributes["SortDirection"] + "<br />";

            //比较排序方向，同时赋值新的排序方向
            ColumnSortDirection = (GV_BackorderDetailAttributes == ColumnSortDirection ? "Descending" : "Ascending");

            //使用排序方向Bind数据
            GridView_BackorderDetail_DataBind(OrgCode, ClsCode, PluCode, ColumnSortDirection);
        }

        protected void Button_ShowBackorderDetail_Click(object sender, EventArgs e)
        {
            //清除调试信息
            Label_ErrorMsg.Text = "";

            GridView_BackorderDetail.EmptyDataText = "您的查询条件没有结果。";

            OrgCode = DropDownList_SelectOrgCode.SelectedValue;

            //ClsCode = TextBox_InputClsCode.Text;
            ClsCode = DropDownList_InputClsCode.SelectedValue;

            PluCode = TextBox_InputPluCode.Text;

            //使用DropDownList不需要
            //if (ClsCode.Equals(""))
            //{
            //    ClsCode = "全部";
            //}

            if (PluCode.Equals(""))
            {
                PluCode = "全部";
            }

            //2015-01-15，ClsCode列增加排序
            //GridView_BackorderDetail.Attributes.Add("SortExpression","ClsCode");
            //GridView_BackorderDetail.Attributes.Add("SortDirection", "ASC");

            GridView_BackorderDetail_DataBind(OrgCode, ClsCode, PluCode, GridView_BackorderDetail.SortDirection.ToString());
        }

        protected void DropdownList_ShowOrgNames()
        {
            DropDownList_SelectOrgCode.Items.Clear();

            String SelectCommandString = "";

            if (IsUserInZb)
            {
                DropDownList_SelectOrgCode.Items.Add(new ListItem("全部", "all"));
                SelectCommandString = "SELECT OrgCode,OrgName FROM [dbo].[u_cls_Org] ORDER BY OrgCode";
            }
            else
            {
                SelectCommandString = "SELECT OrgCode,OrgName FROM [dbo].[u_cls_Org] WHERE Id = '" + GetOrgIdByUserName(UserName) + "' ORDER BY OrgCode";
            }

            SqlConnection SqlConnection = new SqlConnection("Data Source=192.168.0.241;Initial Catalog=cls_forms_db;Persist Security Info=True;User ID=sa;Password=My.SA");
            SqlConnection.Open();

            SqlCommand SelectCommand = new SqlCommand(SelectCommandString, SqlConnection);
            SqlDataReader OrgCodeReader = SelectCommand.ExecuteReader();

            try
            {
                while (OrgCodeReader.Read())
                {
                    DropDownList_SelectOrgCode.Items.Add(new ListItem(OrgCodeReader["OrgCode"].ToString() + "-" + OrgCodeReader["OrgName"].ToString(), OrgCodeReader["OrgCode"].ToString()));
                }
            }
            catch (SqlException e)
            {
                Label_ErrorMsg.Text = "DropdownList_ShowOrgNames() 发生 SqlException，e.Message：" + e.Message + "<br />";
            }

            OrgCodeReader.Close();
            SelectCommand.Dispose();
            SqlConnection.Close();
        }

        protected void Button_Return_Click(object sender, EventArgs e)
        {
            Response.Redirect("BackorderMgr.aspx");
        }

        protected void GridView_BackorderDetail_SelectedIndexChanged(object sender, EventArgs e)
        {
            GridView_BackorderDetail.SelectedRow.Focus();
        }

        //参考
        //http://msdn.microsoft.com/zh-cn/library/system.web.ui.webcontrols.gridview.sortexpression(v=vs.110).aspx
        // This is a helper method used to determine the index of the
        // column being sorted. If no column is being sorted, -1 is returned.
        protected int GetSortColumnIndex()
        {

            // Iterate through the Columns collection to determine the index
            // of the column being sorted.
            foreach (DataControlField field in GridView_BackorderDetail.Columns)
            {
                if (field.SortExpression == GridView_BackorderDetail.SortExpression)
                {
                    return GridView_BackorderDetail.Columns.IndexOf(field);
                }
            }

            return -1;
        }

        //参考
        //http://msdn.microsoft.com/zh-cn/library/system.web.ui.webcontrols.gridview.sortexpression(v=vs.110).aspx
        // This is a helper method used to add a sort direction
        // image to the header of the column being sorted.
        protected void SetSortString(int columnIndex, GridViewRow headerRow)
        {
            //以下为原始内容
            //
            //// Create the sorting image based on the sort direction.
            //Image sortImage = new Image();
            //if (CustomersGridView.SortDirection == SortDirection.Ascending)
            //{
            //    sortImage.ImageUrl = "~/Images/Ascending.jpg";
            //    sortImage.AlternateText = "Ascending Order";
            //}
            //else
            //{
            //    sortImage.ImageUrl = "~/Images/Descending.jpg";
            //    sortImage.AlternateText = "Descending Order";
            //}

            //// Add the image to the appropriate header cell.
            //headerRow.Cells[columnIndex].Controls.Add(sortImage);
            //原始内容结束

            //
            if (GridView_BackorderDetail.SortDirection == SortDirection.Ascending)
            {
                //headerRow.Cells[columnIndex].Controls.
            }
        }

        protected String GetSortDirection(String column)
        {

            // By default, set the sort direction to ascending.
            string sortDirection = "ASC";

            // Retrieve the last column that was sorted.
            string sortExpression = ViewState["SortExpression"] as string;

            if (sortExpression != null)
            {
                // Check if the same column is being sorted.
                // Otherwise, the default value can be returned.
                if (sortExpression == column)
                {
                    string lastDirection = ViewState["SortDirection"] as string;
                    if ((lastDirection != null) && (lastDirection == "ASC"))
                    {
                        sortDirection = "DESC";
                    }
                }
            }

            // Save new values in ViewState.
            ViewState["SortDirection"] = sortDirection;
            ViewState["SortExpression"] = column;

            return sortDirection;
        }

        protected void Button_Export_Click(object sender, EventArgs e)
        {
            //文件名只能是.xls，.xlsx会导致文件无法打开（Office 2013 X64）
            ExportToExcel(null, GridView_BackorderDetail, OrgCode + "_" + UserName + "_" + DateTime.Now + "_导出.xls");
        }

        //参考资料
        //http://mattberseth.com/blog/2007/04/export_gridview_to_excel_1.html
        //http://www.c-sharpcorner.com/UploadFile/DipalChoksi/exportxl_asp22_dc04022007235740PM/exportxl_asp22_dc.aspx?ArticleID=1195fe8c-c6f5-4d52-925b-953f4b9de344
        private void ExportToExcel(string FileType, GridView SourceGV, string FileName)
        {
            //参考资料
            //http://mattberseth.com/blog/2007/04/export_gridview_to_excel_1.html
            //http://www.cnblogs.com/sparon/archive/2007/04/06/702946.html
            //
            //Office 2007 File Format MIME Types for HTTP Content Streaming
            //http://blogs.msdn.com/b/vsofficedeveloper/archive/2008/05/08/office-2007-open-xml-mime-types.aspx

            HttpContext.Current.Response.Clear();
            HttpContext.Current.Response.AddHeader(
                "content-disposition", string.Format("attachment; filename={0}", FileName));

            //HttpContext.Current.Response.ContentType = "application/ms-excel";
            HttpContext.Current.Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";

            using (StringWriter sw = new StringWriter())
            {
                using (HtmlTextWriter htw = new HtmlTextWriter(sw))
                {
                    //  Create a table to contain the grid
                    Table table = new Table();

                    //  include the gridline settings
                    table.GridLines = SourceGV.GridLines;

                    //  add the header row to the table
                    if (SourceGV.HeaderRow != null)
                    {
                        ShowBackorder.PrepareControlForExport(SourceGV.HeaderRow);
                        table.Rows.Add(SourceGV.HeaderRow);
                    }

                    //  add each of the data rows to the table
                    foreach (GridViewRow row in SourceGV.Rows)
                    {
                        ShowBackorder.PrepareControlForExport(row);
                        table.Rows.Add(row);
                    }

                    //  add the footer row to the table
                    if (SourceGV.FooterRow != null)
                    {
                        ShowBackorder.PrepareControlForExport(SourceGV.FooterRow);
                        table.Rows.Add(SourceGV.FooterRow);
                    }

                    //  render the table into the htmlwriter
                    table.RenderControl(htw);

                    //  render the htmlwriter into the response
                    HttpContext.Current.Response.Write(sw.ToString());
                    HttpContext.Current.Response.End();
                }
            }
        }

        private static void PrepareControlForExport(Control control)
        {
            for (int i = 0; i < control.Controls.Count; i++)
            {
                Control current = control.Controls[i];
                if (current is LinkButton)
                {
                    control.Controls.Remove(current);
                    control.Controls.AddAt(i, new LiteralControl((current as LinkButton).Text));
                }
                else if (current is ImageButton)
                {
                    control.Controls.Remove(current);
                    control.Controls.AddAt(i, new LiteralControl((current as ImageButton).AlternateText));
                }
                else if (current is HyperLink)
                {
                    control.Controls.Remove(current);
                    control.Controls.AddAt(i, new LiteralControl((current as HyperLink).Text));
                }
                else if (current is DropDownList)
                {
                    control.Controls.Remove(current);
                    control.Controls.AddAt(i, new LiteralControl((current as DropDownList).SelectedItem.Text));
                }
                else if (current is CheckBox)
                {
                    control.Controls.Remove(current);
                    control.Controls.AddAt(i, new LiteralControl((current as CheckBox).Checked ? "True" : "False"));
                }

                if (current.HasControls())
                {
                    ShowBackorder.PrepareControlForExport(current);
                }
            }
        }

        public override void VerifyRenderingInServerForm(Control control)
        { }

        protected void Button_MutiResp_Click(object sender, EventArgs e)
        {
            if (TextBox_MRespPluCode.Text.Length != 9)
            {
                TextBox_MRespPluCode.ForeColor = Color.Red;
                TextBox_MRespPluCode.Text = "请请正确填写商品编码（长度9位）。";
            }
            else if (TextBox_MutiRespMsg.Text.Equals(""))
            {
                TextBox_MutiRespMsg.ForeColor = Color.Red;
                TextBox_MutiRespMsg.Text = "回复内容不可为空。";
            }
            else
            {
                String MResPluCode = TextBox_MRespPluCode.Text;
                String RespMsg = TextBox_MutiRespMsg.Text;

                if (CheckBox_OverWrite.Checked)
                {
                    //调试信息
                    //Label_ErrorMsg.Text = "CheckBox_OverWrite.Checked";
                    DoMutiResp(MResPluCode, RespMsg, true);
                }
                else
                {
                    //调试信息
                    //Label_ErrorMsg.Text = "CheckBox_OverWrite.Checked false";
                    DoMutiResp(MResPluCode, RespMsg, false);
                }
            }
            
            GridView_BackorderDetail_DataBind(OrgCode, ClsCode, PluCode, GridView_BackorderDetail.SortDirection.ToString());
        }

        protected void DoMutiResp(String PluCode, String RespMsg, Boolean OverWrite)
        {
            SqlConnection SqlConnection = new SqlConnection("Data Source=192.168.0.241;Initial Catalog=cls_forms_db;Persist Security Info=True;User ID=sa;Password=My.SA");
            SqlConnection.Open();

            SqlCommand UpdateCommand = new SqlCommand();

            String UpdateString = "";

            if (OverWrite)
            {
                UpdateString = "UPDATE [dbo].[u_cls_Backorder_Table] SET [ClsResp] = @RespMsg WHERE [PluCode] = @PluCode AND ImportDatatime IN (SELECT LastInsDatetime FROM (SELECT OrgCode, LastInsDatetime FROM [dbo].[u_cls_LastInsDatetime] WHERE ApplicationName = 'Backorder' GROUP BY OrgCode,LastInsDatetime) LID)";
                UpdateCommand.CommandText = UpdateString;
                UpdateCommand.CommandType = CommandType.Text;
                UpdateCommand.Connection = SqlConnection;

                UpdateCommand.Parameters.Add("@PluCode", SqlDbType.NChar, 9);
                UpdateCommand.Parameters.Add("@RespMsg", SqlDbType.NVarChar, 4000);

                UpdateCommand.Parameters["@PluCode"].Value = PluCode;
                UpdateCommand.Parameters["@RespMsg"].Value = RespMsg;
            }
            else
            {
                UpdateString = "UPDATE [dbo].[u_cls_Backorder_Table] SET [ClsResp] = @RespMsg WHERE [PluCode] = @PluCode AND ClsResp IS NULL AND ImportDatatime IN (SELECT LastInsDatetime FROM (SELECT OrgCode, LastInsDatetime FROM [dbo].[u_cls_LastInsDatetime] WHERE ApplicationName = 'Backorder' GROUP BY OrgCode,LastInsDatetime) LID)";
                UpdateCommand.CommandText = UpdateString;
                UpdateCommand.CommandType = CommandType.Text;
                UpdateCommand.Connection = SqlConnection;

                UpdateCommand.Parameters.Add("@PluCode", SqlDbType.NChar, 9);
                UpdateCommand.Parameters.Add("@RespMsg", SqlDbType.NVarChar, 4000);

                UpdateCommand.Parameters["@PluCode"].Value = PluCode;
                UpdateCommand.Parameters["@RespMsg"].Value = RespMsg;
            }

            try
            {
                UpdateCommand.ExecuteNonQuery();
            }
            catch (SqlException se)
            {
                Label_ErrorMsg.Text = "UpdateCommand.CommandText：" + UpdateCommand.CommandText + "<br />";
                Label_ErrorMsg.Text += "SqlException.Message：" + se.Message;
                Label_ErrorMsg.Visible = true;
            }

            UpdateCommand.Dispose();
            SqlConnection.Close();           
        }
    }
}